<template>
  <div class="categoryManagement">
    <div class="operate-container">
      <div class="leftArea">
        <el-input
          v-model="searchParams.name"
          style="width: 240px"
          placeholder="请输入类目名称"
        />
        <el-button
          class="marginLeft14"
          type="primary"
          @click="handleSearch">
          查询
        </el-button>
      </div>
      <div class="rightArea">
        <el-button
          type="primary"
          @click="handleCreateCategory">
          新增分类
        </el-button>
      </div>
    </div>
    <div class="inner-container">
      <el-table
        :height="'calc(100vh - 245px + 50px)'"
        v-loading="loading"
        stripe
        :data="tableData"
        default-expand-all
        row-key="id"
      >
        <el-table-column align="left" fixed label="序号" type="index" width="55"></el-table-column>
        <el-table-column align="left" label="分类名称" prop="name"></el-table-column>
        <el-table-column label="主图">
          <template #default="scope">
            <el-image
              v-if="scope.row.picFile && scope.row.picFile.hasOwnProperty('url')"
              :preview-src-list="[scope.row.picFile.url]"
              :src="scope.row.picFile.url"
              :preview-teleported="true"
              style="width: 48px; height: 48px"
              z-index="100"
              fit="contain">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column align="left" label="排序" prop="sort" width="140"></el-table-column>
        <el-table-column align="left" label="备注" prop="remark"></el-table-column>
        <el-table-column align="left" label="是否显示" prop="status" width="140">
          <template #default="scope">
            <span>{{ scope.row.status === "1" ? '显示' : '隐藏' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="right" label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEditCategory(scope.row)">
              编辑
            </el-button>
            <el-popconfirm
              title="确定删除?"
              confirm-button-text="确定"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="#626AEF"
              @confirm="handleDeleteCategory(scope.row)">
              <template #reference>
                <el-button size="small" type="danger">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500"
      :before-close="handleCloseDialog">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="auto">
        <el-form-item label="父级分类" prop="parentId">
          <el-select
            v-model="ruleForm.parentId"
            placeholder="请选择">
            <el-option label="顶级分类" :value="0"/>
            <el-option
              v-for="item in tableData"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="分类主图" prop="picFile" v-if="ruleForm.parentId !== 0">
          <el-upload
            class="avatar-uploader"
            accept="image/*"
            ref="upload"
            :action="uploadUrl"
            :headers="headers"
            :show-file-list="false"
            :on-success="(res) => handlePicSuccess(res, 'picFile')">
            <img
              v-if="ruleForm.picFile && ruleForm.picFile.hasOwnProperty('url')"
              :src="ruleForm.picFile.url"
              class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmitDialog">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script setup>
import { getToken } from "@/utils/auth";
import { listCategory, addCategory, updateCategory, delCategory, getCategory } from "@/api/category/index.js";
import { ElMessage } from 'element-plus';
import {handleConfirmDelete} from "@/utils/myUtils.js";

const searchParams = reactive({
  name: "",
})

//列表数据获取
onMounted(() => { getTableData() })
const tableData = ref([]);
const loading = ref(false)
const getTableData = () => {
  loading.value = true
  const params = {
    ...searchParams,
  }
  listCategory(params).then(response => {
    tableData.value = response.data;
    loading.value = false;
  })
}

const handleSearch = () => {
  getTableData();
}

//新增与编辑
const dialogVisible = ref(false)
const dialogTitle = ref("");
const ruleFormRef = ref(null);
const ruleForm = reactive({
  id: undefined,
  name: '',  //分类名称
  parentId: undefined,  //父级分类
  picFile: null
})
const rules = reactive({
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
  ],
  parentId: [
    { required: true, message: '请输入分类等级', trigger: 'blur' },
  ],
  picFile: [
    { required: true, message: '请上传分类主图', trigger: 'blur' },
  ],
})

const handleCloseDialog = () => {
  dialogVisible.value = false;
  ruleFormRef.value.resetFields()
}
const handleSubmitDialog = async() => {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      const params = { ...ruleForm }
      if (dialogTitle.value === "新增分类") {
        addCategory(params).then(response => {
          ElMessage.success('新增成功')
          getTableData();
          handleCloseDialog();
        })
      } else if (dialogTitle.value === "编辑分类") {
        updateCategory(params).then(response => {
          ElMessage.success('编辑成功')
          getTableData();
          handleCloseDialog();
        })
      }
    }
  })
}

// 上传的图片服务器地址
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload")
const headers = ref({ Authorization: "Bearer " + getToken() })
const handlePicSuccess = (response, fieldName) => {
  const { id, fileName, oldName, url } = response;
  ruleForm[fieldName] = { id, name: fileName, url, route: oldName }
}

//新增分类
const handleCreateCategory = () => {
  ruleForm.id = undefined;
  ruleForm.name = '';
  ruleForm.parentId = undefined;
  ruleForm.picFile = null;
  dialogTitle.value = "新增分类";
  dialogVisible.value = true;
}

//编辑分类
const handleEditCategory = (data) => {
  const { id } = data;
  getCategory(id).then(response => {
    const { data } = response;
    const { id, name, parentId, picFile  } = data;
    ruleForm.id = id;
    ruleForm.name = name;
    ruleForm.parentId = parentId;
    ruleForm.picFile = picFile;
    dialogTitle.value = "编辑分类";
    dialogVisible.value = true;
  })
}

//删除分类
const handleDeleteCategory = async (data) => {
  await handleConfirmDelete();
  const { id } = data;
  delCategory(id).then(response => {
    ElMessage.success("删除成功")
    getTableData();
  })
}
</script>
<style lang="scss" scoped>
.categoryManagement {
  width: 100%;
  padding: 15px;
  >div.operate-container {
    width: 100%;
    height: 60px;
    padding: 0 15px;
    box-sizing: border-box;
    margin-bottom: 15px;
    background-color: #f5f6f8;
    display: flex;
    align-items: center;
    justify-content: space-between;
    >div.leftArea {
      span {
        color: #343d59;
        font-size: 14px;
        &:not(:first-child) {
          margin: 0 14px;
        }
      }
      .el-select {
        width: 200px;
        :deep( .el-input__inner ){
          height: 30px !important;
        }
      }
    }
    >div.rightArea {

    }
  }
  >div.inner-container {
    div.pagination {
      height: 40px;
      line-height: 40px;
      background-color: #ffffff;
      margin-top: 10px;
      .el-pagination {
        float: right;
        margin-right: 30px;
      }
    }
  }
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  text-align: center;
}
</style>
